<?php
namespace app\api\controller;

use app\common\model\AgentManage;
use app\common\model\Coupons;
use app\common\model\Orders;
use app\common\model\User;
use app\common\model\UserAccount;
use think\Db;
use app\common\model\Types;
use app\common\model\Shops;
use think\facade\Request;
use think\facade\Session;
use wxpay\JsapiPay;

class Api extends Base
{
    /**
     * 首页分类
     * ty_status为首页显示
     * @return \think\response\Json|void
     */
    public function getMent(){
        $map['ty_status'] = ['ty_status','=',1];
        if ($this->request->param('ty_status') == 2) {
            $map['ty_status'] = ['ty_status','=',2];
        }
        //return $this->getOutput(200,'ok',$map);
        $types = Types::where($map)->limit(9)->select();
        foreach ($types as $k => $v) {
            $types[$k]['ty_ico'] = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/'.$v['ty_ico'];
        }
        return $this->getOutput(200,'ok',$types);
    }
    /**
     * 推荐店铺
     * @return \think\response\Json|void
     */
    public function getGroomshop(){
        
        $shop = shops::where('sp_audit', 1)->field('sp_id,sp_name,sp_logo_url')->limit(6)->select();
        foreach ($shop as $k => $v) {
            $shop[$k]['sp_logo_url'] = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/'.$v['sp_logo_url'];
        }
        return $this->getOutput(200,'ok',$shop);

    }
    /**
     * 距离范围推荐
     */
    public function getLongshop(){
        if(!empty($this->request->post('jing'))){
            //使用此函数计算得到结果后，带入sql查询。
            $jing = $this->request->post('jing');
            $wei = $this->request->post('wei');
            $squares = returnSquarePoint($jing, $wei, 5);//参数分别为经纬度 和距离单位公里
            $info_sql = "select sp_id,sp_name,sp_latitude,sp_longitude,sp_logo_url from `rbw_shops` where sp_audit = 1 and sp_latitude>{$squares['right-bottom']['lat']} and sp_latitude<{$squares['left-top']['lat']} and sp_longitude>{$squares['left-top']['lng']} and sp_longitude<{$squares['right-bottom']['lng']} order by ((sp_latitude-$wei)*(sp_latitude-$wei)+(sp_longitude-$jing)*(sp_longitude-$jing)) limit 6";
            /*在lat和lng上建立一个联合索引后，使用此项查询，每条记录的查询消耗平均为0.8毫秒，相比以前的1700ms，真的是天壤之别啊。效率真真的是以前的2125倍~~*/
            $res = Db::query($info_sql);
            foreach ($res as $k => $v) {
                $res[$k]['sp_logo_url'] = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/'.$v['sp_logo_url'];
            }
            return $this->getOutput(200,'JWok',$res);
        }else{
            $shop = shops::where('sp_audit', 1)->field('sp_id,sp_name,sp_logo_url')->limit(6)->select();
            foreach ($shop as $k => $v) {
                $shop[$k]['sp_logo_url'] = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/'.$v['sp_logo_url'];
            }
            return $this->getOutput(200,'ok',$shop);
        }
    }
    /**
     * 
     */
    public function getNum(){
        $sp_tyid = $this->request->param('sp_tyid');
        $jing = $this->request->param('jing');
        $wei = $this->request->param('wei');
        if(isset($sp_tyid)&&isset($jing)&&isset($wei)){
            $squares = returnSquarePoint($jing, $wei, 5);//参数分别为经纬度 和距离单位公里
            $count = "select count(*) as num from `rbw_shops` where sp_audit = 1 and sp_tyid = {$sp_tyid} and sp_latitude>{$squares['right-bottom']['lat']} and sp_latitude<{$squares['left-top']['lat']} and sp_longitude>{$squares['left-top']['lng']} and sp_longitude<{$squares['right-bottom']['lng']} order by ((sp_latitude-$wei)*(sp_latitude-$wei)+(sp_longitude-$jing)*(sp_longitude-$jing))";
            $num = Db::query($count);
            return $this->getOutput(200,'Ok',array('num'=>$num[0]['num']));
        }else{
            return $this->getOutput(400,'No','参数出错');
        }
    }
    /**
     * 店铺
     * 通用页店铺
     * @return \think\response\Json|void
     */
    public function getShop(){
        //定义当前分类ID
        $sp_tyid = $this->request->param('sp_tyid');
        if(is_numeric($this->request->param('page'))){
            $page = $this->request->param('page');
            $num = $this->request->param('num',2);
            $page = $page*$num;
        }else{
            $page = 0;
        }
        if(isset($sp_tyid)){
            $ty_name = Types::get($sp_tyid);
            if(!empty($this->request->param('jing'))){
                //使用此函数计算得到结果后，带入sql查询。
                $jing = $this->request->param('jing');
                $wei = $this->request->param('wei');
                
                $squares = returnSquarePoint($jing, $wei, 5);//参数分别为经纬度 和距离单位公里
               
                $info_sql = "select sp_id,sp_name,sp_latitude,sp_longitude,sp_logo_url,sp_person_flow from `rbw_shops` where sp_audit = 1 and sp_tyid = {$sp_tyid} and sp_latitude>{$squares['right-bottom']['lat']} and sp_latitude<{$squares['left-top']['lat']} and sp_longitude>{$squares['left-top']['lng']} and sp_longitude<{$squares['right-bottom']['lng']} order by ((sp_latitude-$wei)*(sp_latitude-$wei)+(sp_longitude-$jing)*(sp_longitude-$jing)) limit {$page},{$num}";
                /*在lat和lng上建立一个联合索引后，使用此项查询，每条记录的查询消耗平均为0.8毫秒，相比以前的1700ms，真的是天壤之别啊。效率真真的是以前的2125倍~~*/
                $res = Db::query($info_sql);
                //根据经纬 求出距离 getdistance(纬度1,经度1,$lng2,$lat2)
                foreach ($res as $k => $v) {
                    $res[$k]['range'] = ceil(getdistance($v['sp_latitude'],$v['sp_longitude'],$wei,$jing)*1000);
                }
                foreach ($res as $k => $v) {
                    //判断距离
                    if($res[$k]['range'] >= 1000){
                        $res[$k]['range'] = ($v['range']/1000).'千米';
                    }else if($res[$k]['range'] == 0){
                        $res[$k]['range'] = '小于50米';
                    }else{
                        $res[$k]['range'] = $v['range'].'米';
                    }
                    $res[$k]['sp_logo_url'] = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/'.$v['sp_logo_url'];
                }
                //结果是否有
                if($res){
                    return $this->getOutput(200,'ok',array('ty_name'=>$ty_name['ty_name'],'shops'=>$res));
                }
            //如果没有经纬度
            }else{
                $sp = Shops::where('sp_tyid',$sp_tyid)->field('sp_id,sp_tyid,sp_name,sp_logo_url')->select();
                foreach ($sp as $k => $v) {
                    $sp[$k]['sp_logo_url'] = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/'.$v['sp_logo_url'];
                }
                return $this->getOutput(200,'ok',array('ty_name'=>$ty_name['ty_name'],'shops'=>$sp)); 
            }
        }else{
            return $this->getOutput(400,'no','sp_tyid无效');
        }
    }
    /**
     * [getMents 通用页分类]
     * @return [type] [description]
     */
    public function getMents(){

    }
    /**
     * 店铺
     * 单店铺详情
     * @return \think\response\Json|void
     */
    public function getDetail(){
        //传店铺ID 首先需要店铺信息 名称和logo 然后查询改店铺下的所有商品
        $sp_id = $this->request->param('sp_id');

        $arr = array();
        $sp_news = Db::table('rbw_shops')->where('sp_id',$sp_id)->field('sp_id,sp_name,sp_logo_url')->find();
        $sp_news['sp_logo_url'] = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/'.$sp_news['sp_logo_url'];
        $arr['shop'] = $sp_news;
        $gd_news = Db::table('rbw_goods')->where('gd_shop_id',$sp_id)->select();
        foreach ($gd_news as $k => $v) {
            $gd_news[$k]['gd_image_url'] = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/'.$v['gd_image_url'];
        }
        $arr['goods'] = $gd_news;
        return $this->getOutput(200,'ok',$arr);

    }
    /**
     * 搜索店铺
     * 两次请求
     * 纬39.913686,经116.654205 39.930011,116.639443 近 39.923956,116.668282
     * select wei,jing from test order br ((wei-100)*(wei-100)+(jing-100)*(jing-100));
     * wei是纬度字段，jing是经度字段，test是你存的表，现在查的是离（100，100）这个点由近到远排序的
     * @return \think\response\Json|void
     */
    public function getSearch(){
        //按照距离查询
        // 逆地址解析 http://apis.map.qq.com/ws/geocoder/v1/?address=北京市通州区新华西街73号&key=4M6BZ-4F6HG-MUSQI-ISCYF-43DFV-27FNV
        if(!empty($this->request->post('j'))){
            $j = $this->request->post('j');
            $sp_name = $this->request->post('sp_name');
            $w = $this->request->post('w');
          $shopLong = Db::query("select sp_id,sp_name,sp_logo_url from rbw_shops where sp_name like "."'%{$sp_name}%'". " order by ((sp_latitude-{$w})*(sp_latitude-{$w})+(sp_longitude-{$j})*(sp_longitude-{$j}))");
          foreach ($shopLong as $k => $v) {
              $shopLong[$k]['sp_logo_url'] = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/'.$v['sp_logo_url'];
          }
          return $this->getOutput(200,'ok',$shopLong);
        }
        //first
        if(!empty($this->request->post('searchOne'))){
            $sp_name = $this->request->post('searchOne');
            $shopOne = Shops::where('sp_name','like','%'.$sp_name.'%')->where('sp_audit',1)->field('sp_id,sp_name,sp_logo_url')->select();
            foreach ($shopOne as $k => $v) {
                $shopOne[$k]['sp_logo_url'] = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/'.$v['sp_logo_url'];
            }
            //dump($shopOne);
            return $this->getOutput(200,'ok',$shopOne);
        }
        //second
        if(!empty($this->request->post('searchToo'))){
            $sp_name = $this->request->post('searchToo');
            $shopToo = Shops::where('sp_name','like','%'.$sp_name.'%')->where('sp_audit',1)->field('sp_id,sp_name,sp_logo_url')->select();
            foreach ($shopToo as $k => $v) {
                $shopToo[$k]['sp_logo_url'] = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/'.$v['sp_logo_url'];
            }
            //dump($shopToo);
            return $this->getOutput(200,'ok',$shopToo);
        }
    }

    /**
     * 支付商户信息
     * @return \think\response\Json
     */
    public function shopinfo(){
        $sp_id = $this->request->get('sp_id');
        $shop = Shops::where('sp_id',$sp_id)->field("sp_id,concat('"."https:://".$_SERVER['HTTP_HOST']."/"."',sp_logo_url) sp_logo_url,sp_name")->find();
        return $this->getOutput(200,'ok',$shop);
    }

    /**
     * 微信支付
     */
    public function wxpay(){
        $shop_id = $this->request->post('sp_id');//店铺id
        $money = $this->request->post('money');//支付金额
        $shop = Shops::get($shop_id);//获取商户信息
        if(!$shop){//商户不存在
            return $this->getOutput(4003,'商户不存在');
        }
        $unionid= $this->request->post('unionid');//unionid
        if(!$unionid){
            return $this->getOutput(4000,'unionid不能为空');
        }
        $user = User::with('userAccount')->where('unionid',$unionid)->find();
//        $user = User::with('userAccount')->where('openid','1231321')->find();

        if(!$user){
            return $this->getOutput(4004,'当前id不存在，请重新登录');
        }
        $data = array(
        'ord_num' => 'wx'.date("Ymdhis").substr(time(),-5).$shop_id.$user['id'],//平台订单
        'ord_user_id' => $user['id'],//用户id
        'ord_shop_id' => $shop_id,//商户id
        'ord_status' => -1,//付款状态
        'ord_total_price' => $money*100,//订单金额  分
        'ord_create_time' => time(),//订单创建时间
        'ord_agent' => $shop['sp_agem_id'],//代理ID
        'ord_agent_ratio' => $shop['sp_ratio'],//佣金比例
        'ord_agent_money' => $shop['sp_ratio']*$money*100//代理佣金
        );
        if($user['ua_coupons'] >= $money*100) {//红包金额大于支付金额，不需要付款  弹出红包（限额），代理提成 %o
            $data['ord_wx_no'] = 'wx'.date("Ymdhis").substr(time(),-5).$shop_id.$user['id'];//微信订单
            $data['ord_real_price'] = 0;//实付金额
            $data['ord_cou_price'] = $money * 100;//优惠金额
            $query = Orders::create($data);//创建订单记录
            if($query){//订单创建成功
                //5000 红包抵扣
                return $this->getOutput(5000,'ok',array('id'=>$query->ord_id,'money'=>$money));
            }
            return $this->getOutput(4005,'支付参数出错');
        }else{//支付金额大于红包金额 支付金额-红包金额 = 付款金额 弹出红包（限额） ，代理提成 %o
            $data['ord_cou_price'] = $user['ua_coupons'];//优惠金额
            $data['ord_real_price'] = $money*100 - $user['ua_coupons'];//实付金额
        }
        $query = Orders::create($data);//创建订单记录

        $param['body'] = $shop['sp_name'].'消费'; // 产品介绍
        $param['total_fee'] = $data['ord_real_price']; //实付金额 分
        $param['notify_url'] = url("api/notify",'','',true);  //回调路径

        $param['out_trade_no'] = $data['ord_num']; //订单编号
        $param['attach'] = array('id'=>$query->ord_id);//参数

        $output =  JsapiPay::getParams($param,$user['openid']);//小程序支付参数

        $response = array(
            'code' => 200,
            'message' => 'ok',
            'wxpay' => $output,
            'order' => $data['ord_num'],
        );
        return json($response);

    }

    /**
     * 微信支付回调
     */
    public function notify(){
        //初始化日志
        $xml = file_get_contents("php://input");
        libxml_disable_entity_loader(true);
        $array= json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        if('SUCCESS' === $array['return_code']){
            if('SUCCESS' === $array['result_code']){//支付成功
                $order_arr = json_decode($array['attach'],true);
                $order_id = $order_arr['id'];
                $order = Orders::get($order_id);
                // 启动事务
                Db::startTrans();
                try{
                    $order->ord_wx_no = $array['transaction_id'];//微信订单
                    $order->ord_status = 1;//订单状态
                    $query = $order->save();
//                    file_put_contents('/www/wwwroot/cs.rongbaiwei.com/public/upload/f7.txt',json_encode($query),FILE_APPEND);
                    //代理提成
                    $am = AgentManage::get($order->ord_agent);
                    $r = $am->data(['agem_account'=>$am->agem_account+$order->ord_agent_money,'agem_brokerage'=>$am->agem_brokerage+$order->ord_agent_money])->save();
                    //商户收入记录
                    $shop = Shops::get($order->ord_shop_id);
                    $shop->data(['sp_income'=>$shop->sp_income+($order->ord_total_price*1000-$order->ord_agent_money),
                        'sp_income_rest'=>$shop->sp_income_rest+($order->ord_total_price*1000-$order->ord_agent_money),'sp_person_flow'=>$shop->sp_person_flow+1])->save();
                    //用户红包余额 减额
                    $user = UserAccount::where('ua_user',$order->ord_user_id)->find();
                    $user->data(['ua_coupons'=>$user->ua_coupons - $order->ord_cou_price])->save();

                    $uu = Coupons::create(['cp_user_id'=>$order['ord_user_id'],'cp_shop_id'=>$order->ord_shop_id,'cp_price'=>mt_rand(1,99),'cp_order'=>$array['out_trade_no'],'cp_create_time'=>time()]);
                    Db::commit();
                    ob_clean();
                    $return = '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
                    echo $return;die;

                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    Db::name('pay_fail')->insert(array('pf_type'=>1,'pf_rank'=>'user','pf_content'=>json_encode($array),'pf_time'=>time()));
                }
            }else{
                //支付失败
                Db::name('pay_fail')->insert(array('pf_type'=>1,'pf_rank'=>'user','pf_content'=>json_encode($array),'pf_time'=>time()));
            }
        }
    }

    /**
     * 红包支付回调
     */
    public function coupons_notify(){
        $unionid = $this->request->post('unionid');//unionid 获取openid
        if(!$unionid){
            return $this->getOutput(4000,'unionid不能为空！');
        }
       $id = $this->request->post('id');
       $order = Orders::get($id);
        // 启动事务
        Db::startTrans();
        try{
            $order->ord_status = 1;//订单状态
            $query = $order->save();
            //代理提成
            $am = AgentManage::get($order->ord_agent);
            $r = $am->data(['agem_account'=>$am->agem_account+$order->ord_agent_money,'agem_brokerage'=>$am->agem_brokerage+$order->ord_agent_money])->save();
            //商户收入记录
            $shop = Shops::get($order->ord_shop_id);
            $shop->data(['sp_income'=>$shop->sp_income+($order->ord_total_price*1000-$order->ord_agent_money),
                'sp_income_rest'=>$shop->sp_income_rest+($order->ord_total_price*1000-$order->ord_agent_money),'sp_person_flow'=>$shop->sp_person_flow+1])->save();
            //用户红包余额 减额
            $user = UserAccount::where('ua_user',$order->ord_user_id)->find();
            $user->data(['ua_coupons'=>$user->ua_coupons - $order->ord_cou_price])->save();

            $uu = Coupons::create(['cp_user_id'=>$order['ord_user_id'],'cp_shop_id'=>$order->ord_shop_id,'cp_price'=>mt_rand(1,99),'cp_order'=>$order['ord_num'],'cp_create_time'=>time()]);
            Db::commit();
            return $this->getOutput(200,'ok',array('order'=>$order['ord_num']));
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            Db::name('pay_fail')->insert(array('pf_type'=>1,'pf_rank'=>'user','pf_content'=>json_encode($array),'pf_time'=>time()));
        }
//            }else{
//                //支付失败
//                Db::name('pay_fail')->insert(array('pf_type'=>1,'pf_rank'=>'user','pf_content'=>json_encode($array),'pf_time'=>time()));
//            }
//        }
    }

    /**
     * 红包提示接口
     */
    public function get_coupons(){
        $unionid = $this->request->post('unionid');//unionid 获取openid
        $order = $this->request->post('order'); //订单编号
        if(!$unionid){
            return $this->getOutput(4000,'unionid不存在');
        }
        $coupon = Coupons::where('cp_order',$order)->field("cp_user_id,CONVERT(cp_price / 100 ,DECIMAL(18,2)) cp_price")->find();
        if(!$coupon){
            return $this->getOutput(4009,'无红包');
        }

        UserAccount::where('ua_user',$coupon->cp_user_id)->setInc('ua_coupons',$coupon->cp_price*100);
        return $this->getOutput(200,'ok',$coupon);
    }



}